<template>
    <div class="tab">
        <cube-tab-bar
                v-model="selectedLabel"
                show-slider
                class="border-bottom-1px"
                ref="tabBar"
                :useTransition="false"
        >
            <cube-tab v-for="v in tabs" :label="v.label" :icon="v.icon">
            </cube-tab>
        </cube-tab-bar>
        <cube-slide
        :initialIndex="index"
        :autoPlay="false"
        :loop="false"
        @change="onChange"
        @scroll="onScroll"
        :options="slideOption"
        ref="slide"
        class="slide">
            <cube-slide-item v-for="tab in tabs">
                <component ref="component" :is="tab.component"></component>
            </cube-slide-item>
        </cube-slide>

    </div>
</template>

<script>
    export default {
        name: "tab",
        props:{
            initialIndex: Number,
            data: Array,
        },
        data(){
            return{
                index: this.initialIndex|| 0,
                tabs: this.data|| [{label: 'Tab 0'}],
                slideOption: {
                    probeType:3,
                    listenScroll:true,
                }
            }
        },
        computed:{
            selectedLabel:{
                get:function(){ return this.tabs[this.index].label},
                set:function(v){
                    this.index= this.tabs.findIndex((obj)=>{
                        return obj.label===v
                    })
                }
            }
        },
        methods:{
            onScroll(pos){
                let m=this.$refs.slide.slide.scrollerWidth
                let n=this.$refs.tabBar.$el.clientWidth
                let x=-pos.x/m*n
                this.$refs.tabBar.setSliderTransform(x)
            },
            onChange(index){
                this.index=index
                let inst= this.$refs.component[index]
                if(inst.fetch)
                    inst.fetch();
                bus.$emit('msg_changeTab', index, this.$options.name)
            }
        },
        mounted(){
            this.onChange(this.index)
        }

    }
</script>

<style scoped lang="stylus">
    .tab
        flex:1
        display:flex
        flex-direction: column
        .slide
            flex:1
            height:auto
</style>